// src/main/java/com/nb/controller/DeptController.java
package com.nb.controller;

import com.mybatisflex.core.paginate.Page;
import com.nb.annotation.LogAsync;
import com.nb.dto.DeptCreateDTO;
import com.nb.dto.DeptStructureUpdateDTO;
import com.nb.dto.DeptUpdateDTO;
import com.nb.dto.DeptUserQueryDTO;
import com.nb.entity.Dept;
import com.nb.entity.User;
import com.nb.result.Result;
import com.nb.service.DeptService;
import com.nb.vo.DeptDetailVO;
import com.nb.vo.DeptTreeVO;
import jakarta.validation.constraints.Min;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 部门控制器
 */
@RestController
@RequestMapping("/dept")
@Slf4j
public class DeptController {

    @Autowired
    private DeptService deptService;

    /**
     * 创建新的部门
     *
     * @param deptCreateDTO 部门创建信息
     * @return 结果
     */
    @PostMapping("/create")
    public Result createDept(@Validated @RequestBody DeptCreateDTO deptCreateDTO) {
        log.info("Received dept creation request: {}", deptCreateDTO);

        // 调用服务层创建部门
        Long deptId = deptService.createDept(deptCreateDTO);

        return Result.success(deptCreateDTO);
    }

    @PutMapping("/update")
    public Result updateDept(@Validated @RequestBody DeptUpdateDTO deptUpdateDTO) {
        log.info("Received dept update request: {}", deptUpdateDTO);

        // 调用服务层更新部门
        boolean success = deptService.updateDept(deptUpdateDTO);

        if (success) {
            return Result.success("部门更新成功");
        }
        return Result.error("部门更新失败");
    }
    @DeleteMapping("/delete/{id}")
    public Result deleteDept(@PathVariable Long id) {
        log.info("Received dept delete request, id: {}", id);

        // 校验ID合法性
        if (id == null || id <= 0) {
            throw new IllegalArgumentException("部门ID不能为负数或空");
        }

        // 调用服务层执行删除
        int success = deptService.deleteDept(id);
        if (success > 0) {
            return Result.success("部门删除成功");
        }

        return Result.error("删除失败，部门不存在或已被删除（ID：" + id + "）");
    }
    @GetMapping("/list")
    public Result getDeptPage(
            @RequestParam(defaultValue = "1") @Min(value = 1, message = "页码必须大于等于1") Integer pageNum,
            @RequestParam(defaultValue = "10") @Min(value = 1, message = "每页条数必须大于等于1") Integer pageSize,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Long parentId) {

        // 限制每页最大条数（避免查询压力）
        if (pageSize > 100) {
            pageSize = 100;
        }

        log.info("Received dept page query: pageNum={}, pageSize={}, name={}, parentId={}",
                pageNum, pageSize, name, parentId);

        Page<Dept> deptPage = deptService.getDeptPage(pageNum, pageSize, name, parentId);
        return Result.success(deptPage);
    }

    @LogAsync(value = "查询部门详情", recordParams = true)
    @GetMapping("/detail/{id}")
    public Result getDeptDetail(@PathVariable @Min(value = 1, message = "部门ID必须大于等于1") Long id) {
        log.info("Received dept detail query: id={}", id);

        DeptDetailVO deptVO = deptService.getDeptDetail(id);
        if (deptVO == null) {
            log.warn("Dept not found or deleted: id={}", id);
            return Result.error("部门不存在或已被删除");
        }

        return Result.success(deptVO);
    }
    @GetMapping("/tree")
    public Result getDeptTree() {
        log.info("Received dept tree query request");
        List<DeptTreeVO> deptTree = deptService.getDeptTree();
        return Result.success(deptTree);
    }
    @GetMapping("/users")
    public Result getDeptUsers(@Validated DeptUserQueryDTO queryDTO) {
        log.info("Received dept users query: deptId={}, pageNum={}, pageSize={}",
                queryDTO.getDeptId(), queryDTO.getPageNum(), queryDTO.getPageSize());

        // 限制最大每页条数（避免查询压力）
        if (queryDTO.getPageSize() > 100) {
            queryDTO.setPageSize(100);
        }

        Page<User> userPage = deptService.getDeptUsers(queryDTO);
        return Result.success(userPage);
    }

    /**
     * 批量调整部门层级关系和排序
     */
    @PutMapping("/structure")
    public Result updateDeptStructure(@Validated @RequestBody DeptStructureUpdateDTO updateDTO) {
        log.info("Received dept structure update request, total depts: {}",
                updateDTO.getDeptNodes().size());

        boolean success = deptService.batchUpdateStructure(updateDTO);
        if (success) {
            return Result.success("部门结构调整成功");
        }
        return Result.error("部门结构调整失败");
    }
}